package Homework;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

//服务器端
public class Server {

	@SuppressWarnings("resource")
	public static void main(String[] args) {
		//创建服务器端的套接字，传入端口号
		ServerSocket serverSocket=null;
		Socket socket=null;
		DataInputStream dis=null;
		DataOutputStream dos=null;
		Scanner scanner = new Scanner(System.in);
		 
		try {
			serverSocket = new ServerSocket(8876);
			//启动服务器
			System.out.println("服务器启动了。。。。。。");
			//接收客户端发来的信息
			socket = serverSocket.accept();
			System.out.println("受理了客户端"+socket.getInetAddress().getHostAddress()+"："+socket.getPort()+"的请求！");
			
			//创建输入输出流读取和回复客户端的信息
			dis = new DataInputStream(socket.getInputStream());
			dos = new DataOutputStream(socket.getOutputStream());
			
			//读取客户端发送的请求
			String infoFromClient = dis.readUTF();
			System.out.println("收到了客户端发来的信息："+infoFromClient);
			
			//回复客户端的请求
			System.out.println("请输入回复客户端的信息：");
			String info=scanner.next();
			dos.writeUTF(info);
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				dos.close();
				dis.close();
				socket.close();
				serverSocket.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
